package com.greatwqs.wmall.common.provider.config;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.util.Locale;

/**
 * 国际化
 *
 * @author wang-qingsong
 */
@Slf4j
@Configuration
public class I18nConfig {

    @Value("${spring.messages.basename}")
    private String baseName;

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        log.warn("I18nConfig messageSource baseName: {}", baseName);
        messageSource.setBasename(baseName);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    /**
     * Springboot web 自动解析 Locale，获取方式：<p>
     * 1. Controller API 方法中直接声明获取 Locale locale <p>
     * 2. LocaleContextHolder.getLocale();
     */
    @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
        resolver.setDefaultLocale(Locale.CHINA);
        return resolver;
    }
}
